package generic.net;

import java.beans.XMLDecoder;
import java.io.InputStream;


/**
 * Allows Messages to be passed back and forth over a stream.
 *
 * Unlike the normal XMLEncoder, the MessageInputStream can pass multiple
 * messages in both directions.
 *
 * @see MessageOutputStream
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class MessageInputStream {
    private InputStream in;

    /**
     * Creates a new MessageInputStream on top of the given input stream.
     * @param in The input Stream to send messages down.
     */
    public MessageInputStream(InputStream in) {
        this.in = in;
    }

    /**
     * Read a message from the stream. Will block until a message has arived.
     * @return  The message.
     */
    public Message read() {
        SubInputStream sistream = new SubInputStream(in);
        if (sistream.available() > 0) {
            return (Message) new XMLDecoder(sistream).readObject();
        } else {
            return null;
        }


    }
}
